package api;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;

/**
 * 小象代理短效代理IP示例 - JAVA，类库 jsoup
 *
 * @author xxdl
 */
public class JsoupDemo {

    // 应用账号（请替换为真实账号）
    private static String appKey = "appKey";
    // 应用密码（请替换为真实密码）
    private static String appSecret = "appSecret";

    private static String api = "https://api.xiaoxiangdaili.com/ip/get?appKey=%s&appSecret=%s&cnt=1&wt=text";
    private static int timeout = 10000;

    private static Proxy getProxy() throws IOException {
        Document doc = Jsoup.connect(String.format(api, appKey, appSecret)).ignoreContentType(true).get();

        if (doc != null) {
            String content = doc.text();
            System.out.println("API response: " + content);
            if (!StringUtils.isEmpty(content)) {
                String[] splits = content.split(":");
                if (splits.length == 2) {
                    return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(splits[0], Integer.parseInt(splits[1])));
                }
            }
        }
        return null;
    }

    public static void getUrlContent(String url) throws IOException {
        // JDK 8u111版本后，目标页面为HTTPS协议，启用proxy用户密码鉴权
        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");

        Authenticator.setDefault(new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(appKey, appSecret.toCharArray());
            }
        });

        Connection connect = Jsoup.connect(url)
                .header("Accept-Encoding", "gzip")
                .timeout(timeout)
                .ignoreContentType(true)
                .proxy(getProxy());
        Document document = connect.get();
        System.out.println("Target response：" + document.text());
    }

    public static void main(String[] args) throws Exception {
        // 要访问的目标页面
        String targetUrl = "http://httpbin.org/ip";
        for (int i = 0; i < 3; i++) {
            getUrlContent(targetUrl);
            Thread.sleep(10000);
        }
    }
}
